from django.conf import settings
from django.core.management.base import BaseCommand
from home_application.models import Business, Set, Module, Host
from blueking.component.shortcuts import get_client_by_user
from django.contrib.auth import get_user_model
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "同步CMDB数据到本地数据库"

    def handle(self, *args, **options):
        # 使用服务账号认证
        client = get_client_by_user("yourname")

        # 1. 同步业务
        biz_result = client.cc.search_business({"fields": ["bk_biz_id", "bk_biz_name"]})
        if not biz_result.get("result"):
            logger.error("同步业务失败: %s", biz_result.get("message"))
            return
        for biz in biz_result["data"]["info"]:
            Business.objects.update_or_create(
                bk_biz_id=biz["bk_biz_id"],
                defaults={"bk_biz_name": biz["bk_biz_name"]}
            )
        logger.info("同步业务完成")

        # 2. 同步集群
        for biz in biz_result["data"]["info"]:
            sets_result = client.cc.search_set({
                "bk_biz_id": biz["bk_biz_id"],
                "fields": ["bk_set_id", "bk_set_name", "bk_biz_id"]
            })
            if not sets_result.get("result"):
                logger.error("同步集群失败: %s", sets_result.get("message"))
                continue
            for s in sets_result["data"]["info"]:
                Set.objects.update_or_create(
                    bk_set_id=s["bk_set_id"],
                    defaults={
                        "bk_set_name": s["bk_set_name"],
                        "bk_biz_id_id": s["bk_biz_id"]
                    }
                )
        logger.info("同步集群完成")

        # 3. 同步模块
        for s in Set.objects.all():
            modules_result = client.cc.search_module({
                "bk_biz_id": s.bk_biz_id_id,
                "bk_set_id": s.bk_set_id,
                "fields": ["bk_module_id", "bk_module_name", "bk_set_id", "bk_biz_id"]
            })
            if not modules_result.get("result"):
                logger.error("同步模块失败: %s", modules_result.get("message"))
                continue
            for m in modules_result["data"]["info"]:
                Module.objects.update_or_create(
                    bk_module_id=m["bk_module_id"],
                    defaults={
                        "bk_module_name": m["bk_module_name"],
                        "bk_set_id_id": m["bk_set_id"],
                        "bk_biz_id_id": m["bk_biz_id"]
                    }
                )
        logger.info("同步模块完成")

        # 4. 同步主机
        for biz in biz_result["data"]["info"]:
            hosts_result = client.cc.list_biz_hosts({
                "bk_biz_id": biz["bk_biz_id"],
                "page": {"start": 0, "limit": 1000, "sort": ""},
                "fields": [
                    "bk_host_id", "bk_cloud_id", "bk_host_innerip", "bk_os_type",
                    "bk_mac", "operator", "bk_bak_operator"
                ]
            })
            if not hosts_result.get("result"):
                logger.error("同步主机失败: %s", hosts_result.get("message"))
                continue
            for h in hosts_result["data"]["info"]:
                Host.objects.update_or_create(
                    bk_host_id=h["bk_host_id"],
                    defaults={
                        "bk_cloud_id": h.get("bk_cloud_id"),
                        "bk_host_innerip": h.get("bk_host_innerip"),
                        "bk_os_type": h.get("bk_os_type", ""),
                        "bk_mac": h.get("bk_mac", ""),
                        "operator": h.get("operator", ""),
                        "bk_bak_operator": h.get("bk_bak_operator", ""),
                        "bk_biz_id_id": biz["bk_biz_id"]
                    }
                )
        logger.info("同步主机完成")
        self.stdout.write(self.style.SUCCESS("CMDB数据同步完成"))
